﻿using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.UI;
using StampController.BL;
using StampController.BL.Models;
using StampController.Core;
using StampController.Helpers;

namespace StampController.Pages
{
    public partial class ApprovalRequestForm : BasePage
    {        
        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["q"]))
            {
                Response.Redirect("/");
                return;
            }

            var im = new RequestFormImpl();
            var model = im.GetRequestForm(Request.QueryString["q"]);
            if (model == null)
            {
                Response.Redirect("/");
                return;
            }

            if (!IsPostBack)
            {
                var user = SessionUtils.Get<UsersModel>("USER");

                lblDepartment.Text = model.CreatedBy;   // +" - " + model.DeptName + "&nbsp;";
                lblDateOfApp.Text = model.DateRequestText + "&nbsp;";
                lblNeededDate.Text = model.DateNeededText + "&nbsp;";
                lblPagesNo.Text = model.PagesNo + "&nbsp;";
                lblCopiesNo.Text = model.CopiesNo + "&nbsp;";
                lblRemark.Text = model.Remark;
                litPurpose.Text = model.Purpose;
                litRequiredBy.Text = model.RequiredByName + (string.IsNullOrEmpty(model.DefineName) ? "&nbsp;" : string.Format(" ({0})", model.DefineName));
                litStampedType.Text = model.STName + "&nbsp;";
                litStamp.Text = model.StampName + "&nbsp;";
                litSignBy.Text = model.SignByName + "&nbsp;";
                litRequestType.Text = model.RequestTypeName + "&nbsp;";
                litCategory.Text = model.CateName;
                litRequestFor.Text = model.RequestForName;
                hdUserRequest.Value = model.RequestFor ?? model.UserID;
                hdKindOfStamp.Value = model.StampID.ToString(CultureInfo.InvariantCulture);

                // Set current user
                UsersModel delegateUser = null;
                if (model.AssignedTo.HasValue)
                {
                    // Get delegate user
                    delegateUser = GetUser(user.UserID, model.AssignedTo);

                    if (delegateUser == null)
                    {
                        delegateUser = user;
                    }
                    else
                    {
                        // Granted
                        hdAssignedTo.Value = model.AssignedTo.ToString();
                    }

                    if (delegateUser.DeptID != model.AssignedTo)
                    {
                        Response.Redirect("/");
                        return;
                    }
                }

                if (delegateUser != null && delegateUser.IsHOD)
                {
                    assignTo.Visible = drpDept.Visible = false;
                }
                else
                {
                    var deptIm = new DepartmentImpl();
                    var deptList = deptIm.GetDepartmentList();
                    deptList.Remove(deptList.SingleOrDefault(x => delegateUser != null && x.DeptID == delegateUser.DeptID));
                    drpDept.DataSource = deptList;
                    drpDept.DataTextField = "Name";
                    drpDept.DataValueField = "DeptID";
                    drpDept.DataBind();
                }
            }

            var htmlBuilder = new StringBuilder("<table>")
                    .Append("<thead><tr>")
                    .Append("<th class='head-left'>Document attachments:</th>")
                //.Append("<th>Pages</th>")
                //.Append("<th>Copies</th>")
                    .Append("</tr></thead>")
                    .Append("<tbody>");

            if (model.DocumentList != null)
            {
                foreach (var documentModel in model.DocumentList)
                {
                    htmlBuilder.AppendFormat("<tr><td><a href='{0}' target='_blank'>{1}</a></td>", documentModel.Link,
                        documentModel.OriginName);
                    //.AppendFormat("<td class='col-right'>{0}</td>", documentModel.PagesNo)
                    //.AppendFormat("<td class='col-right'>{0}</td></tr>", documentModel.CopiesNo);
                }
            }

            htmlBuilder.Append("</tbody>")
                .Append("</table>");
            pnlUploadFiles.Controls.Add(new LiteralControl(htmlBuilder.ToString()));

            var historyList = new ApprovalHistoryImpl().GetApprovalHistoryList(Request.QueryString["q"]);
            if (historyList.Count > 0)
            {
                htmlBuilder = new StringBuilder("<table>")
                    .Append("<thead>")
                    .Append("<tr><th>Approved By</th>")
                    .Append("<th>Approved Date</th>")
                    .Append("<th>Comment</th>")
                    .Append("<th>Status</th></tr>")
                    .Append("</thead>")
                    .Append("<tbody>");

                foreach (var approvalHistoryModel in historyList)
                {
                    htmlBuilder.AppendFormat("<tr><td>{0}</td>", approvalHistoryModel.ApprovedBy)
                        .AppendFormat("<td class='col-right'>{0}</td>", approvalHistoryModel.ApprovedDate)
                        .AppendFormat("<td>{0}</td>", approvalHistoryModel.Comment)
                        .AppendFormat("<td>{0}</td></tr>", approvalHistoryModel.StatusName);
                }

                htmlBuilder.Append("</tbody>")
                    .Append("</table>");

                pnlApprovalHistory.Controls.Add(new LiteralControl(htmlBuilder.ToString()));
            }
        }

        /// <summary>
        /// Assign to the another department
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void assignedTo_Click(object sender, EventArgs e)
        {
            var requestId = Request.QueryString["q"];
            var userImpl = new UsersImpl();
            // User assign
            UsersModel currentUser = userImpl.GetUser(UserName);
            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (delegateUser.DeptID != null)
            {
                var im = new RequestFormImpl();
                var assignedTo = Convert.ToInt32(drpDept.SelectedValue);
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = assignedTo,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Assigned
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                    history.AuthorizedBy = delegateUser.UserID;
                var result = im.AssignRequestForm(requestId, history);
                if (result)
                {
                    // Send mail for HOD
                    if (currentUser.IsGD)
                    {
                        var request = im.GetRequestForm(requestId);
                        MailHelper.Send(ApprovalStatus.Assigned, UserType.GD, currentUser, request, "/pages/ApprovalRequestForm.aspx");
                    }
                    Response.Redirect("/Pages/");
                }
            }
        }

        protected void reject_Click(object sender, EventArgs e)
        {
            var requestId = Request.QueryString["q"];
            var im = new RequestFormImpl();
            var userImpl = new UsersImpl();
            // Rejected user 
            UsersModel currentUser = userImpl.GetUser(UserName);

            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (delegateUser.DeptID.HasValue)
            {
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = delegateUser.DeptID.Value,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Rejected
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                {
                    history.AuthorizedBy = delegateUser.UserID;
                }
                var result = im.RejectRequestForm(requestId, history);
                if (result)
                {
                    // Send to User
                    var request = im.GetRequestForm(requestId);
                    if (currentUser.IsHOD)
                    {
                        // HOD
                        MailHelper.Send(ApprovalStatus.Rejected, UserType.HOD, currentUser, request, "/pages/ApprovalRequestForm.aspx",
                            history);
                    }
                    else if (currentUser.IsGD)
                    {
                        // GD
                        MailHelper.Send(ApprovalStatus.Rejected, UserType.GD, currentUser, request, "/pages/ApprovalRequestForm.aspx",
                            history);
                    }
                    Response.Redirect("/Pages/");
                }
            }
        }

        /// <summary>
        /// Approve to complete (unless user is not the GD and category is null 
        /// or category in HOD can't complete)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void approve_Click(object sender, EventArgs e)
        {
            int? assignedTo = null;

            var requestId = Request.QueryString["q"];
            var im = new RequestFormImpl();
            var userImpl = new UsersImpl();
            var categoryImpl = new CategoryImpl();

            // Approver
            UsersModel currentUser = userImpl.GetUser(UserName);

            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (!delegateUser.IsGD)
            {
                // Gd only approve to complete (assigned to is null)
                CategoryModel cate = categoryImpl.GetCategory(requestId);
                if (cate == null || !cate.HODComplete)
                {
                    assignedTo = Common.GdDept;
                }
            }

            if (delegateUser.DeptID.HasValue)
            {
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = delegateUser.DeptID.Value,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Approval
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                {
                    history.AuthorizedBy = delegateUser.UserID;
                }
                var result = im.ApproveRequestForm(requestId, history, assignedTo);
                if (result)
                {
                    var request = im.GetRequestForm(requestId);
                    if (currentUser.IsHOD)
                    {
                        // HOD
                        MailHelper.Send(ApprovalStatus.Approval, UserType.HOD, currentUser, request, "/pages/ApprovalRequestForm.aspx", history);
                    }
                    else if (currentUser.IsGD)
                    {
                        // GD completes this request
                        MailHelper.Send(ApprovalStatus.Approval, UserType.GD, currentUser, request,
                            "/pages/AdminConfirmForm.aspx",
                            history);
                    }

                    Response.Redirect("/Pages/");
                }
            }
        }

        /// <summary>
        /// Assign to the another department
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void old_assignedTo_Click(object sender, EventArgs e)
        {
            var requestId = Request.QueryString["q"];
            var userImpl = new UsersImpl();
            // User assign
            UsersModel currentUser = userImpl.GetUser(UserName);
            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (delegateUser.DeptID != null)
            {
                var im = new RequestFormImpl();
                var assignedTo = Convert.ToInt32(drpDept.SelectedValue);
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = assignedTo,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Assigned
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                    history.AuthorizedBy = delegateUser.UserID;
                var result = im.AssignRequestForm(requestId, history);
                if (result)
                {
                    // Send mail for HOD
                    var usrImpl = new UsersImpl();
                    var usr = usrImpl.GetHod(assignedTo);
                    if (usr != null)
                    {
                        var request = im.GetRequestForm(requestId);
                        MailHelper.Send(usr, "/pages/ApprovalRequestForm.aspx", request);
                    }
                    Response.Redirect("/Pages/");
                }
            }
        }

        protected void old_reject_Click(object sender, EventArgs e)
        {
            var requestId = Request.QueryString["q"];
            var im = new RequestFormImpl();
            var userImpl = new UsersImpl();
            // Rejected user 
            UsersModel currentUser = userImpl.GetUser(UserName);

            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (delegateUser.DeptID.HasValue)
            {
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = delegateUser.DeptID.Value,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Rejected
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                {
                    history.AuthorizedBy = delegateUser.UserID;
                }
                var result = im.RejectRequestForm(requestId, history);
                if (result)
                {
                    // Send to User
                    var request = im.GetRequestForm(requestId);
                    MailHelper.Send(currentUser, "/pages/ApprovalRequestForm.aspx", request, history);
                    Response.Redirect("/Pages/");
                }
            }
        }
        protected void old_approve_Click(object sender, EventArgs e)
        {
            int? assignedTo = null;

            var requestId = Request.QueryString["q"];
            var im = new RequestFormImpl();
            var userImpl = new UsersImpl();
            var categoryImpl = new CategoryImpl();

            // Approver
            UsersModel currentUser = userImpl.GetUser(UserName);

            // Set to delegate user
            var delegateUser = currentUser;
            if (!string.IsNullOrEmpty(hdAssignedTo.Value))
            {
                delegateUser = GetUser(currentUser.UserID, int.Parse(hdAssignedTo.Value)) ?? currentUser;
            }

            if (!delegateUser.IsGD)
            {
                // Gd only approve to complete (assigned to is null)
                CategoryModel cate = categoryImpl.GetCategory(requestId);
                if (cate == null || !cate.HODComplete)
                {
                    assignedTo = Common.GdDept;
                }
            }

            if (delegateUser.DeptID.HasValue)
            {
                var history = new ApprovalHistoryModel
                {
                    Fullname = currentUser.Name,
                    ApprovedBy = currentUser.UserID,
                    ApprovedDate = DateTime.Now,
                    DeptID = delegateUser.DeptID.Value,
                    Comment = txtComment.Text,
                    Status = (int)ApprovalStatus.Approval
                };
                if (!string.IsNullOrEmpty(hdAssignedTo.Value))
                {
                    history.AuthorizedBy = delegateUser.UserID;
                }
                var result = im.ApproveRequestForm(requestId, history, assignedTo);
                if (result)
                {
                    var request = im.GetRequestForm(requestId);
                    var usrImpl = new UsersImpl();
                    var usr = usrImpl.GetHod(request.AssignedTo);
                    if (usr != null && request.AssignedTo == Common.GdDept)
                    {
                        // Send to GD
                        MailHelper.Send(usr, "/pages/ApprovalRequestForm.aspx", request, history);
                    }

                    if (assignedTo == null)
                    {
                        // Complete
                        // SiteID = 1 (Cty - HN), SiteID = 2 (CN - HCM)
                        usr = userImpl.GetAdminOfficer(int.Parse(hdKindOfStamp.Value));
                        if (usr != null)
                        {
                            // Send to admin
                            MailHelper.Send(usr, "/pages/AdminConfirmForm.aspx", request, history);

                            // Send to usr
                            MailHelper.Send(delegateUser, "/pages/ViewRequestForm.aspx", request, history);
                        }
                    }

                    Response.Redirect("/Pages/");
                }
            }
        }
        #endregion

        private static UsersModel GetUser(string userId, int? deptId)
        {
            var imAuthorized = new AuthorizedHistoryImpl();
            return imAuthorized.GetAuthorizedPerson(userId, DateTime.Now, deptId);
        }
    }
}